#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int n = gas.size();
        vector<int> diff(n);
        for (int i = 0; i < n; i++) diff[i] = gas[i] - cost[i];
        int ret = 0;
        while (ret < n)
        {
            if (diff[ret] < 0)
            {
                ret++;
                continue;
            }
            int cur = ret, tmp = n, sum = 0;
            while (tmp--)
            {
                cur %= n;
                sum += diff[cur++];
                if (sum < 0)
                {
                    if (ret >= cur) return -1;
                    ret = cur;
                    break;
                }
            }
            if (tmp == -1) return ret;
        }
        return -1;
    }
};